﻿<%@ WebHandler Language="C#" Class="traceHandler" %>

using System;
using System.Web;
using System.Data;
using Chenxin.Lib.Utility;
using System.Data.SqlClient;
using System.Collections.Generic;

public class traceHandler : AjaxHandlerBase
{
    public traceHandler()
    {
        htTypePermit.Add("del", Constants.Permit_TraceDel);
        htTypePermit.Add("add", Constants.Permit_TraceAdd);
    }
    
    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            case "add"://跟单
                strResponse = addTrace(context);
                break;
            case "getlist":
                //strResponse = getTraceList(context);
                strResponse = GetList(context);
                break;
            case "del":
                strResponse = delTrace(context);
                break;
                //hejifeng add 2010-04-27
            case "gethousetrace":
                strResponse = getHouseTraceList(context);
                break;
            case "getviewownerlist":
                strResponse=GetViewOwnerList(context);
                break;
            case "addtracelist":
                strResponse = addCache(context);
                break;
            case "getcounterfeilist":
                strResponse = GetcounterfeiList(context);
                break;
            case "alldel":
                strResponse = AllDel(context);
                break;
            case "remove":
                strResponse = Remove(context);
                break; 
            default:
                break;
        }
        context.Response.Write(strResponse);
    }

    private string Remove(HttpContext context)
    {
        try
        {
            string traceid = context.Request.Params["id"];
            if (string.IsNullOrEmpty(traceid))
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "跟单标识丢失，请联系管理员！");
            //要比較的房屋列表
            Dictionary<string, Chenxin.Lib.House.Entity.House_TraceInfo> tracelist;
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.COUNTERFEIT_TRACE, CurrentUserInfo.UserId.ToString());
            //从Cache中查找
            tracelist = cs.GetObject(strCacheKey) as Dictionary<string, Chenxin.Lib.House.Entity.House_TraceInfo>;
            if (cs.Hit)
            {
                //当前房源ID添加到列表中
                tracelist.Remove(traceid);
                //设定Cache中的存活期
                cs.Set(strCacheKey, tracelist);
                return retExecResult(Constants.ExecResult.Succ, "移出成功！", "");
            }
            else
            {
                return retExecResult(Constants.ExecResult.Succ, "记录不存在！", "");
            }
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }

    }
    private string AllDel(HttpContext context)
    {
        try
        {
            //要比較的房屋列表
            Dictionary<string, Chenxin.Lib.House.Entity.House_TraceInfo> tracelist;
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.COUNTERFEIT_TRACE, CurrentUserInfo.UserId.ToString());
            //从Cache中查找
            tracelist = cs.GetObject(strCacheKey) as Dictionary<string, Chenxin.Lib.House.Entity.House_TraceInfo>;

            //未命中
            if (cs.Hit)
            {
                cs.Delete(strCacheKey);
               return retExecResult(Constants.ExecResult.Succ, "删除成功！", "");
            }
            else
            {
                return retExecResult(Constants.ExecResult.Succ, "无记录！", "");
            }
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }

    }
    private string GetcounterfeiList(HttpContext context)
    {
      try
      {
        Dictionary<string, Chenxin.Lib.House.Entity.House_TraceInfo> traceList;
        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
        string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.COUNTERFEIT_TRACE, CurrentUserInfo.UserId.ToString());
        //从Cache中查找
        traceList = cs.GetObject(strCacheKey) as Dictionary<string, Chenxin.Lib.House.Entity.House_TraceInfo>;

        //有比较房源数据
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (traceList != null && traceList.Keys.Count > 0)
        {
            sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
            sb.Append("<thead>");
            sb.Append("<tr><th style=\"width:55px\">操作</th>");
            sb.Append("<th>编号：</th>");
            sb.Append("<th>地址：</th>");
            sb.Append("<th>跟单时间：</th>");
            sb.Append("<th>跟单人：</th>");
            sb.Append("</tr></thead>");
            sb.Append("<tbody>");
            int i = 0;
            foreach (KeyValuePair<String, Chenxin.Lib.House.Entity.House_TraceInfo> dic in traceList)
            {
                Chenxin.Lib.House.Entity.House_TraceInfo trace = dic.Value;
                if (i % 2 == 0)
                    sb.AppendFormat("<tr class=\"tr_houselist\">");
                else
                    sb.AppendFormat("<tr class=\"tr_houselist bluebgcolor\" >");
                sb.AppendFormat("<td width=\"15%\">{0}</td>", string.Format("<a href=\"javascript:void(0)\" name=\"{0}\" class=\"tr_del\">移出</a>", trace.TraceId));
                sb.AppendFormat("<td width=\"22%\" >{0}</td>", trace.HouseCode);
                sb.AppendFormat("<td width=\"28%\" >{0}</td>", trace.HouseAddress);
                sb.AppendFormat("<td width=\"20%\" >{0}</td>", trace.TraceTime);
                sb.AppendFormat("<td width=\"15%\" >{0}</td>", trace.Tractor + "/" + trace.Depart);
                sb.Append("</tr>");
                if (i % 2 == 0)
                    sb.AppendFormat("<tr class=\"tabline\" title=\"{0}\"><td height=\"29\" colspan=\"9\">{0}</td></tr>", trace.TraceContext);
                else
                    sb.AppendFormat("<tr class=\"tr_houselist bluebgcolor\" title=\"{0}\"><td height=\"29\" colspan=\"9\">{0}</td></tr>", trace.TraceContext);
                i++;
            }
            sb.Append("</tbody></table>");
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", traceList.Count, sb.ToString());
        }
        else {

            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", 0, sb.ToString());
        }
        
      }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }
 
    private string addCache(HttpContext context)
    {
        try
        {
            string traceid = context.Request.Params["id"];
            if (string.IsNullOrEmpty(traceid))
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "跟单标识丢失，请联系管理员！");

            Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo = Chenxin.Lib.House.DAL.House_TraceInfo.GetModel(new Guid(traceid));
            //要比較的房屋列表
            Dictionary<string, Chenxin.Lib.House.Entity.House_TraceInfo> tracelist;

            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.COUNTERFEIT_TRACE, CurrentUserInfo.UserId.ToString());
            //从Cache中查找
            tracelist = cs.GetObject(strCacheKey) as Dictionary<string, Chenxin.Lib.House.Entity.House_TraceInfo>;

            //未命中
            if (!cs.Hit)
            {
                //如果Cache中没有信息,将当前的房源ID添加到Cache中
                tracelist = new Dictionary<string, Chenxin.Lib.House.Entity.House_TraceInfo>();
                //当前房源ID添加到列表中
                tracelist.Add(traceid, house_TraceInfo);
                //设定Cache中的存活期
                cs.Set(strCacheKey, tracelist);
                return retExecResult(Constants.ExecResult.Succ, "添加成功！", "");
            }
            else
            {
                if (tracelist == null)
                {
                    tracelist = new Dictionary<string, Chenxin.Lib.House.Entity.House_TraceInfo>();
                }
                //不在Cache列表中的场合
                if (!tracelist.ContainsKey(traceid))
                {
                    //添加到列表中
                    tracelist.Add(traceid, house_TraceInfo);
                }
                //重新添加
                cs.Set(strCacheKey, tracelist);

                return retExecResult(Constants.ExecResult.Succ, "添加成功！", "");
            }
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }

    }
    
    private string GetViewOwnerList(HttpContext context)
    {
        try
        {
            if (context.Request["houseid"] != null && context.Request["employeeid"]!=null)
            {
                string strWhere = "1=1";
                string order = " AddTime desc";

                int pageSize = 10;
                int pageIndex = 1;
                int count = 0;

                if (context.Request["pagesize"] != null)
                {
                    pageSize = Convert.ToInt32(context.Request["pagesize"]);
                }
                if (context.Request["pageindex"] != null)
                {
                    pageIndex = Convert.ToInt32(context.Request["pageindex"]) + 1;
                }

                if (context.Request["sort"] != null && context.Request["sort"] != "")
                {
                    order = context.Request["sort"];
                }
                strWhere += string.Format(" and HouseId='{0}'", context.Request["houseid"]);
                strWhere += string.Format(" and ViewEmployeeId='{0}'", context.Request["employeeid"]);

                DataSet ds = null;

                if (pageIndex == 1)
                {
                    //分页第一页从缓存中读取
                    Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                    string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_VIEWOWNER + "." + pageIndex.ToString(), context.Request["houseid"]);

                    ds = cs.GetDataSet(strCachKey);
                    if (!cs.Hit)
                    {
                        //若未命中。从查询数据库中读取
                        ds = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(pageIndex, pageSize, order, "House_ViewOwerInfo", strWhere, "*", "*", true);
                        if (ds != null)
                            cs.Set(strCachKey, ds, DateTime.Now.AddMinutes(5));
                    }
                }
                else
                {
                    ds = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(pageIndex, pageSize, order, "House_ViewOwerInfo", strWhere, "*", "*", true);
                }

                

//                DataSet ds = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(pageIndex, pageSize, order, "House_ViewOwerInfo", strWhere, "*", "*", true);
                count = Convert.ToInt32(ds.Tables[1].Rows[0].ItemArray[0]);
                return string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", count, JsonHelp.Convert2Json(ds.Tables[0]));
                //return string.Format("{{success:'1',msg:'',data:{{html:'{0}',count:{1}}}}}", CreateGrid(ds.Tables[0], "HouseCode,HouseAddress,Employee,Depart,Addtime", "RecoredId"), count);
            }
            else
            {
                return string.Format("{{success:'0',msg:'获取记录失败！',data:{{html:'',count:0}}}}");
            }
        }
        catch(Exception e)
        {
            return string.Format("{{success:'0',msg:'获取记录失败！"+e.Message+"',data:{{html:'',count:0}}}}");            
        }
    }

    /// <summary>
    /// 获取列表
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetList(HttpContext context)
    {
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            string fieldlist = "*";
            string fieldtablelist = "*";
            string orderfield = "House_TraceInfo.TraceTime desc";

            Guid cityId = (string.IsNullOrEmpty(context.Request["cityid"])) ? CurrentUserInfo.CityId : new Guid(context.Request["cityid"]);
            Guid companyId = (string.IsNullOrEmpty(context.Request["companyid"])) ? CurrentUserInfo.CompanyId : new Guid(context.Request["companyid"]);
            Guid areaId = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departId = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

            int tracetype = (string.IsNullOrEmpty(context.Request["tracetype"])) ? 1000 : int.Parse(context.Request["tracetype"]);
            string keyword = context.Request["keyword"];
            string stime = context.Request["stime"];
            string etime = context.Request["etime"];
            string counterfeittrace = context.Request["counterfeittrace"];

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append("(IsHide = 0)");//非隐藏跟单

            if (!string.IsNullOrEmpty(stime)) sb.AppendFormat(" AND (TraceTime >='{0}')", stime);
            if (!string.IsNullOrEmpty(etime)) sb.AppendFormat(" AND (TraceTime <'{0}')", DateTime.Parse(etime).AddDays(1).ToString("yyyy-MM-dd"));
            if ("10".Equals(counterfeittrace))
            {

                sb.AppendFormat(" and (select count(*) from House_ViewOwerInfo where House_TraceInfo.HouseId = House_ViewOwerInfo.HouseId ");
                sb.AppendFormat(" and House_TraceInfo.TractorId = House_ViewOwerInfo.ViewEmployeeId)<1 ");
            }
            if (tracetype != 1000) sb.AppendFormat(" AND (status = {0})", tracetype);

            if (userId != Guid.Empty)
                sb.AppendFormat(" AND (TractorId = '{0}') ", userId);
            else if (departId != Guid.Empty)
                sb.AppendFormat(" AND (DepartId = '{0}')", departId);
            else if (areaId != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, areaId);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(areaId);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");

                sb.Append(" AND (EXISTS(");
                sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
                sb.AppendFormat("WHERE (House_TraceInfo.DepartId = M.Departid AND M.DepartSrc like '{0}%'))) ", item.DepartSrc);
                //sb.AppendFormat(" AND (DepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (companyId != Guid.Empty)
            {
                sb.Append(" AND (EXISTS(");
                sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
                sb.AppendFormat("WHERE (House_TraceInfo.DepartId = M.Departid AND M.CompanyId='{0}'))) ", companyId);
                //sb.AppendFormat(" AND (DepartId in (Select DepartId from v_Hr_DepartmentInfo where CompanyId = '{0}'))", companyId);
            }
            else if (cityId != Guid.Empty)
            {
                sb.Append(" AND (EXISTS(");
                sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
                sb.AppendFormat("WHERE (House_TraceInfo.DepartId = M.Departid AND M.CityId='{0}'))) ", cityId);

                //sb.AppendFormat(" AND (DepartId in (Select DepartId from v_Hr_DepartmentInfo where CityId = '{0}'))", cityId);
            }

            if (!string.IsNullOrEmpty(keyword)) sb.AppendFormat(" AND ((HouseCode Like '%{0}%')  OR (HouseAddress Like '%{1}%'))", keyword, keyword);

            //查询范围权限判断
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_Trace_ViewAll))//查看所有跟单
            {

            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_Trace_ViewCity))//查看城市级跟单
            {
                sb.Append(" AND (EXISTS(");
                sb.Append("Select 1 from v_Hr_DepartmentInfo N ");
                sb.AppendFormat("WHERE (House_TraceInfo.DepartId = N.Departid AND N.CityId='{0}'))) ", CurrentUserInfo.CityId);
                //sb.AppendFormat(" AND (DepartId In (Select DepartId from v_Hr_DepartmentInfo Where CityId = '{0}'))", CurrentUserInfo.CityId);
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_Trace_ViewCompany))//查看公司级跟单
            {
                sb.Append(" AND (EXISTS(");
                sb.Append("Select 1 from v_Hr_DepartmentInfo N ");
                sb.AppendFormat("WHERE (House_TraceInfo.DepartId = N.Departid AND N.CompanyId='{0}'))) ", companyId);

                //sb.AppendFormat(" AND (DepartId In (Select DepartId from v_Hr_DepartmentInfo Where CompanyId = '{0}'))", CurrentUserInfo.CompanyId);
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_Trace_ViewDepart))//查看部门级跟单
            {
                sb.Append(" AND (EXISTS(");
                sb.Append("Select 1 from v_Struct_UserDepartRelation N ");
                sb.AppendFormat("WHERE (House_TraceInfo.DepartId = N.Departid AND N.Userid= '{0}' and n.viewtrace=1))) ", CurrentUserInfo.UserId);
            }
            else
            {
                sb.AppendFormat(" AND (TractorId ='{0}')", CurrentUserInfo.UserId);
            }


            System.Data.DataSet dshousetracelist = null;

            dshousetracelist = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(
                iPageIndex, iPageSize, orderfield, "House_TraceInfo", sb.ToString(), fieldlist, fieldtablelist, true);

            int count = (int)dshousetracelist.Tables[1].Rows[0][0];

            return string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", count, JsonHelp.Convert2Json(dshousetracelist.Tables[0]));
        }
        catch(Exception e)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + e.Message);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string getTraceList(HttpContext context)
    {
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            string fieldlist = "*";
            string fieldtablelist = "*";
            string orderfield = "House_TraceInfo.TraceTime desc";
            
            Guid cityId = (string.IsNullOrEmpty(context.Request["cityid"])) ? CurrentUserInfo.CityId: new Guid(context.Request["cityid"]);
            Guid companyId = (string.IsNullOrEmpty(context.Request["companyid"])) ? CurrentUserInfo.CompanyId : new Guid(context.Request["companyid"]);
            Guid areaId = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departId = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);
            
            int tracetype = (string.IsNullOrEmpty(context.Request["tracetype"])) ? 1000 : int.Parse(context.Request["tracetype"]);
            string keyword = context.Request["keyword"];
            string stime = context.Request["stime"];
            string etime = context.Request["etime"];
            string counterfeittrace = context.Request["counterfeittrace"];
            
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
                            
            sb.Append("(IsHide = 0)");//非隐藏跟单

            if (!string.IsNullOrEmpty(stime)) sb.AppendFormat(" AND (TraceTime >='{0}')", stime);
            if (!string.IsNullOrEmpty(etime)) sb.AppendFormat(" AND (TraceTime <'{0}')", DateTime.Parse(etime).AddDays(1).ToString("yyyy-MM-dd"));
            if ("10".Equals(counterfeittrace)) {

                sb.AppendFormat(" and (select count(*) from House_ViewOwerInfo where House_TraceInfo.HouseId = House_ViewOwerInfo.HouseId ");
               sb.AppendFormat(" and House_TraceInfo.TractorId = House_ViewOwerInfo.ViewEmployeeId)<1 ");
            }
            if (tracetype != 1000) sb.AppendFormat(" AND (status = {0})", tracetype);
                
            if (userId != Guid.Empty)
                sb.AppendFormat(" AND (TractorId = '{0}') ", userId);
            else if (departId != Guid.Empty)
                sb.AppendFormat(" AND (DepartId = '{0}')", departId);
            else if (areaId != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, areaId);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService( Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(areaId);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");

                sb.Append(" AND (EXISTS(");
                sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
                sb.AppendFormat("WHERE (House_TraceInfo.DepartId = M.Departid AND M.DepartSrc like '{0}%'))) ", item.DepartSrc);
                //sb.AppendFormat(" AND (DepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (companyId != Guid.Empty)
            {
                sb.Append(" AND (EXISTS(");
                sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
                sb.AppendFormat("WHERE (House_TraceInfo.DepartId = M.Departid AND M.CompanyId='{0}'))) ", companyId);
                //sb.AppendFormat(" AND (DepartId in (Select DepartId from v_Hr_DepartmentInfo where CompanyId = '{0}'))", companyId);
            }
            else if (cityId != Guid.Empty)
            {
                sb.Append(" AND (EXISTS(");
                sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
                sb.AppendFormat("WHERE (House_TraceInfo.DepartId = M.Departid AND M.CityId='{0}'))) ", cityId);
                
                //sb.AppendFormat(" AND (DepartId in (Select DepartId from v_Hr_DepartmentInfo where CityId = '{0}'))", cityId);
            }

            if (!string.IsNullOrEmpty(keyword)) sb.AppendFormat(" AND ((HouseCode Like '%{0}%')  OR (HouseAddress Like '%{1}%'))", keyword, keyword);
            
            //查询范围权限判断
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_Trace_ViewAll))//查看所有跟单
            {
                
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_Trace_ViewCity))//查看城市级跟单
            {
                sb.Append(" AND (EXISTS(");
                sb.Append("Select 1 from v_Hr_DepartmentInfo N ");
                sb.AppendFormat("WHERE (House_TraceInfo.DepartId = N.Departid AND N.CityId='{0}'))) ", CurrentUserInfo.CityId);
                //sb.AppendFormat(" AND (DepartId In (Select DepartId from v_Hr_DepartmentInfo Where CityId = '{0}'))", CurrentUserInfo.CityId);
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_Trace_ViewCompany))//查看公司级跟单
            {
                sb.Append(" AND (EXISTS(");
                sb.Append("Select 1 from v_Hr_DepartmentInfo N ");
                sb.AppendFormat("WHERE (House_TraceInfo.DepartId = N.Departid AND N.CompanyId='{0}'))) ", companyId);
                
                //sb.AppendFormat(" AND (DepartId In (Select DepartId from v_Hr_DepartmentInfo Where CompanyId = '{0}'))", CurrentUserInfo.CompanyId);
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_Trace_ViewDepart))//查看部门级跟单
            {
                sb.Append(" AND (EXISTS(");
                sb.Append("Select 1 from v_Struct_UserDepartRelation N ");
                sb.AppendFormat("WHERE (House_TraceInfo.DepartId = N.Departid AND N.Userid= '{0}' and n.viewtrace=1))) ", CurrentUserInfo.UserId);
            }
            else
            {
                sb.AppendFormat(" AND (TractorId ='{0}')", CurrentUserInfo.UserId);
            }
            
            
            System.Data.DataSet dshousetracelist = null;
            
            dshousetracelist = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(
                iPageIndex, iPageSize, orderfield, "House_TraceInfo", sb.ToString(), fieldlist, fieldtablelist, true);

            int count = (int)dshousetracelist.Tables[1].Rows[0][0];

            string strHtml = "";
            if (!GetHouseTraceListHtml(dshousetracelist, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml);
            }

            dshousetracelist.Dispose();
            dshousetracelist = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }

    private bool GetHouseTraceListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        try
        {
            Dictionary<string, Chenxin.Lib.House.Entity.House_TraceInfo> traceList;
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.COUNTERFEIT_TRACE, CurrentUserInfo.UserId.ToString());
            //从Cache中查找
            traceList = cs.GetObject(strCacheKey) as Dictionary<string, Chenxin.Lib.House.Entity.House_TraceInfo>;
            
            
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
            sb.Append("<thead>");
            sb.Append("<tr><th width=\"15%\" >操作</th>");
            sb.Append("<th width=\"22%\" >编号</th>");
            sb.Append("<th>地址</th>");
            sb.Append("<th width=\"15%\">跟单时间</th>");
            sb.Append("<th width=\"18%\">跟单人/房源所属人</th>");
            sb.Append("</tr></thead>");
            sb.Append("<tbody>");

            int i = 0;
            foreach(System.Data.DataRow row in dslist.Tables[0].Rows)
            {
                if (i % 2 == 0)
                    sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", row["TraceId"].ToString());
                else
                    sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist bluebgcolor\" >", row["TraceId"].ToString());

                if (traceList != null && traceList.Keys.Count > 0 && traceList.ContainsKey(row["TraceId"].ToString()))
                {
                    sb.AppendFormat("<td>{0}{1}{2}</td>", string.Format("<a href=\"javascript:void(0)\" name=\"{0}\" class=\"tr_deltrace\">删除</a>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TraceId", Guid.Empty)), string.Format(" | <a href=\"javascript:void(0) \" name=\"{0},{1}\" class=\"tr_viewovner\">业主查看记录</a>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseId", Guid.Empty), Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TractorId", Guid.Empty)), string.Format("<br/><span  style=\"color:gray\">添加到虚假跟单</span>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TraceId", Guid.Empty)));
                }
                else
                {
                    sb.AppendFormat("<td>{0}{1}{2}</td>", string.Format("<a href=\"javascript:void(0)\" name=\"{0}\" class=\"tr_deltrace\">删除</a>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TraceId", Guid.Empty)), string.Format(" | <a href=\"javascript:void(0) \" name=\"{0},{1}\" class=\"tr_viewovner\">业主查看记录</a>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseId", Guid.Empty), Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TractorId", Guid.Empty)), string.Format("<br/><a href=\"javascript:void(0) \" name=\"{0}\" class=\"tr_addtracelist\">添加到虚假跟单</a>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TraceId", Guid.Empty)));
                }

                if ("0".Equals(row["status"].ToString()))
                {
                    sb.AppendFormat("<td ><a name=\"{1}\" class=\"a_favor_house\" href=\"ShowDetailInfo.aspx?houseid={1}\" target=\"blank\">{0}</a></td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseCode", ""), Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseId", ""));
                }
                else {
                    sb.AppendFormat("<td >{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseCode", ""));
                }
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseAddress", ""));
                sb.AppendFormat("<td >{0:d}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TraceTime", ""));

                string user = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Tractor", "") + "/" + Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Depart", "");
                user +="<br/>" +Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprPerson", "-") + "/" + Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprDepart", "-");
                sb.AppendFormat("<td >{0}</td>", user);
                sb.Append("</tr>");

                if (i % 2 == 0)
                    sb.AppendFormat("<tr class=\"tabline\" title=\"{0}\"><td height=\"29\" style=\"color:#3E5EF9\" colspan=\"9\">{0}</td></tr>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TraceContext", ""));
                else
                    sb.AppendFormat("<tr class=\"tr_houselist bluebgcolor\" title=\"{0}\"><td height=\"29\" style=\"color:#3E5EF9\" colspan=\"9\">{0}</td></tr>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TraceContext", ""));
                i++;
            }

            sb.Append("</tbody></table>");

            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }
    
    //*******************************************
    //功能概要       ：添加跟单信息
    //参数説明       ：houseid 房源主键 houseCode 房源编号 shouseAddress房源地址 traceContext 跟单内容
    //返回值説明     ：void
    //功能詳細       ：根据房源编号获得房源信息
    //作成者         ：chen.yugong 
    //作成日         ：2010-03-01
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string addTrace(HttpContext context)
    {
         try
         {
             //转换成实体
             Chenxin.Lib.House.Entity.House_TraceInfo model = (Chenxin.Lib.House.Entity.House_TraceInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_TraceInfo));
             if (model.TraceId == null)
                 return string.Format("{{success:'0',msg:'{0}',data:''}}", "跟单标识丢失，请联系管理员！");

             if (model.status != 1)
             {
                 if (model.HouseId == null)
                     return string.Format("{{success:'0',msg:'{0}',data:''}}", "房源标识丢失，请联系管理员！");

                 Chenxin.Lib.House.Entity.House_BaseInfo house_BaseInfo = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(model.HouseId);
                 if (house_BaseInfo == null)
                     return string.Format("{{success:'0',msg:'{0}',data:''}}", "房源信息丢失，请联系管理员！");
                 if (house_BaseInfo.TraceNum == null)
                     house_BaseInfo.TraceNum = 1;
                 else
                     house_BaseInfo.TraceNum = house_BaseInfo.TraceNum + 1;
                 house_BaseInfo.ServiceTime = DateTime.Now;
                 Chenxin.Lib.House.DAL.House_BaseInfo.Update(house_BaseInfo);
                 model.OprDepart = house_BaseInfo.OprDepart;
                 model.OprDepartId = house_BaseInfo.OprDepartId;
                 model.OprPerson = house_BaseInfo.OprPerson;
                 model.OprPersonId = house_BaseInfo.OprPersonId;
                 //清除房源信息缓存
                 string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, house_BaseInfo.HouseId);
                 Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                 cs.Delete(strCachKey);

                 //清除跟单信息缓存
                 string strTraceCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_TRACE + "." + "10", house_BaseInfo.HouseId);
                 //cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
                 cs.Delete(strTraceCachKey);
                 strTraceCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_TRACE + "." + "4", house_BaseInfo.HouseId);
                 cs.Delete(strTraceCachKey);
                 strTraceCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_TRACE + "." + "20", house_BaseInfo.HouseId);
                 cs.Delete(strTraceCachKey);

                 model.status = 0;
             } else {
                 
                 if (model.HouseId == null)
                     return string.Format("{{success:'0',msg:'{0}',data:''}}", "客户标识丢失，请联系管理员！");

                 Chenxin.Lib.House.Entity.Customer_BaseInfo customer_BaseInfo = Chenxin.Lib.House.DAL.Customer_BaseInfo.GetModel(model.HouseId);
                 if (customer_BaseInfo == null)
                     return string.Format("{{success:'0',msg:'{0}',data:''}}", "客户信息丢失，请联系管理员！");
                 customer_BaseInfo.LastTraceDay = System.DateTime.Now;
                 Chenxin.Lib.House.DAL.Customer_BaseInfo.Update(customer_BaseInfo);
                 model.OprDepart = customer_BaseInfo.OprDepart;
                 model.OprDepartId = customer_BaseInfo.OprDepartId;
                 model.OprPerson = customer_BaseInfo.OprPerson;
                 model.OprPersonId = customer_BaseInfo.OprPersonId;
                 
                 string strWhere = string.Format("CustomerId = '{0}'", customer_BaseInfo.CustomerId);
                 List<Chenxin.Lib.House.Entity.Customer_DemandInfo> list = Chenxin.Lib.House.DAL.Customer_DemandInfo.GetListArray(strWhere);
                 for (int i = 0; i < list.Count; i++)
                 {
                     Chenxin.Lib.House.Entity.Customer_DemandInfo customerDemandInfo = list[i];
                     customerDemandInfo.LastTraceDay = DateTime.Now;
                     Chenxin.Lib.House.DAL.Customer_DemandInfo.Update(customerDemandInfo);
                 }

                 Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                 //清除跟单信息缓存
                 string strTraceCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_TRACE + "." + "10", model.HouseId);
                 cs.Delete(strTraceCachKey);
                 strTraceCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_TRACE + "." + "4", model.HouseId);
                 cs.Delete(strTraceCachKey);
                 strTraceCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_TRACE + "." + "20", model.HouseId);
                 cs.Delete(strTraceCachKey);
             }
             //添加用户跟单 2010-5-18 王玮 Add
             AddTrace(model);

             string flg = context.Request["isnotice"];
             //添加提醒
             if ("1".Equals(flg))
             {
                 Chenxin.Lib.House.Entity.FollowClew followClew = (Chenxin.Lib.House.Entity.FollowClew)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["noticemodel"], typeof(Chenxin.Lib.House.Entity.FollowClew));
                 //记录标识	
                 followClew.RecordId = Guid.NewGuid();
                 //所属业务员	
                 followClew.UserName = CurrentUserInfo.UserName;
                 //所属部门	
                 followClew.DepartName = CurrentUserInfo.DepartName;
                 //添加时间	
                 followClew.AddTime = DateTime.Now;
                 //所属部门ID	
                 followClew.DepartId = CurrentUserInfo.DepartId;
                 //所属业务员ID	
                 followClew.UserId = CurrentUserInfo.UserId;
                 //内容	
                 followClew.body = followClew.body.Replace("\r", "\\r");

                 Chenxin.Lib.House.DAL.FollowClew.Add(followClew);
             }

             //添加用户操作日志 2010-5-11 王玮 Add
             AddLog("" + CurrentUserInfo.UserName + "添加了一个跟单:[" + model.HouseAddress + "]已添加跟单。",
                     OperationType.OperationTypeComboList()["OprType_TraceAdd"].ToString());

             return string.Format("{{success:'1',msg:'{0}',data:''}}", "跟单成功！");
         }
         catch (Exception ex)
         {
             return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
         }

    }

    //返回值説明     ：void
    //功能詳細       ：删除
    //作成者         ：chen.yugong 
    //作成日         ：2010-03-01
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string delTrace(HttpContext context)
    {
        try
        {
            //转换成实体
            string traceId = context.Request["modelid"];
            if (traceId == null)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "跟单标识丢失，请联系管理员！");
            Chenxin.Lib.House.Entity.House_TraceInfo model =  Chenxin.Lib.House.DAL.House_TraceInfo.GetModel(new Guid(traceId));
            if (model == null)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "跟单信息不存在！");
            Chenxin.Lib.House.DAL.House_TraceInfo.Delete(new Guid(traceId));

            //清除跟单信息缓存
            string strTraceCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_TRACE, model.HouseId);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            cs.Delete(strTraceCachKey);

            //添加用户操作日志 2010-5-11 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "删除了一个跟单:[" + model.HouseAddress + "]已删除跟单。",
                    OperationType.OperationTypeComboList()["OprType_TraceDel"].ToString());
            
            return string.Format("{{success:'1',msg:'{0}',data:''}}", "删除成功！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }

    }
    
    //返回值説明     ：响应字符串
    //功能詳細       ：某一房屋对应跟单信息
    //作成者         ：hejifeng
    //作成日         ：2010-04-27
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string getHouseTraceList(HttpContext context)
    {
        Guid houseId = (string.IsNullOrEmpty(context.Request["houseid"])) ? Guid.Empty : new Guid(context.Request["houseid"]);
        string responseJson = "";
        try
        {
            if (houseId == Guid.Empty)
            {
                responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，房源标识丢失");
                return responseJson;
            }

            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            string fieldlist = "*";
            string fieldtablelist = "*";
            string orderfield = "House_TraceInfo.TraceTime desc";
            string strwhere = string.Format("(houseId='{0}' AND IsHide = 0 AND Status = 0)", houseId);

            System.Data.DataSet dshousetracelist = null;
            if (iPageIndex == 1)
            {
                //分页第一页从缓存中读取
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_TRACE + "." + iPageSize.ToString(), houseId);

                dshousetracelist = cs.GetDataSet(strCachKey);
                if (!cs.Hit)
                {
                    //若未命中。从查询数据库中读取
                    dshousetracelist = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(
                        iPageIndex, iPageSize, orderfield, "House_TraceInfo", strwhere, fieldlist, fieldtablelist, true);
                    if (dshousetracelist != null && dshousetracelist.Tables[1].Rows.Count > 0)
                        cs.Set(strCachKey, dshousetracelist, DateTime.Now.AddMinutes(10));
                }
            }
            else
            {
                dshousetracelist = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(
                iPageIndex, iPageSize, orderfield, "House_TraceInfo", strwhere, fieldlist, fieldtablelist, true);
            }

            responseJson = retExecResult(Constants.ExecResult.Succ, "", retPagination(dshousetracelist));

            dshousetracelist.Dispose();
            dshousetracelist = null;
            return responseJson;
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }

    //生成html
    private Constants.Pagination retPagination(DataSet ds)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        sb.Append("<table id=\"showGenDan\" width=\"100%\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\"><thead><tr class=\"tab_line4\"><td width=\"25%\">");
        sb.Append("<b>跟盘人</b></td><td width=\"20%\"><b>跟盘时间</b></td><td width=\"52%\"><b>跟盘内容</b></td></tr>");
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            sb.AppendFormat("<tr class=\"tab_line5\"><td  title=\"{0}\">{0}</td><td  title=\"{1}\">{1}</td><td title=\"{2}\">{2}</td></tr>",
                DatasetHelper.GetValue(dr, "Tractor", "-") + "/" + DatasetHelper.GetValue(dr, "Depart", "-"),
                DatasetHelper.GetValue(dr, "TraceTime", DateTime.Today),
                DatasetHelper.GetValue(dr, "TraceContext", ""));

        }
        sb.Append("</thead></table>");

        Constants.Pagination stuPag = new Constants.Pagination();
        stuPag.count = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
        stuPag.data = sb.ToString();

        return stuPag;
    }
    //*******************************************
    //功能概要       ：响应字符串
    //参数説明       ：strMsg 消息 
    //返回值説明     ：void
    //功能詳細       ：权限检查
    //作成者         ：chen.yugong 
    //作成日         ：2010-05-20
    //修改者         ：
    //修改日         ：
    //*******************************************
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        if (context.Request["op"] != null)
        {
            string op = context.Request["op"].ToLower();
            if (op.Equals("del"))
            {
               string traceId = context.Request["modelid"];
               if (string.IsNullOrEmpty(traceId)) {
                    strMsg = "{success:0,msg:'获取数据失败！',data:''}";
                    return false;
               }
               Chenxin.Lib.House.Entity.House_TraceInfo model = null;
               model = Chenxin.Lib.House.DAL.House_TraceInfo.GetModel(new Guid(traceId));
               if (model == null) {
                    strMsg = "{success:0,msg:'获取数据失败！',data:''}";
                    return false;
                }
                //所有
               if (CurrentUserInfo.ContainsPermit(Constants.Permit_DelTrace_All))
                {
                    strMsg = "{success:1,msg:'',data:{permit:true}}";
                    return true;
                }
               else if (CurrentUserInfo.ContainsPermit(Constants.Permit_DelTrace_City))
                {
                    if (CurrentUserInfo.CityId.Equals(model.CityId))
                    {
                        strMsg = "{success:1,msg:'',data:{permit:true}}";
                        return true;
                    }
                    else
                    {
                        strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                        return false;
                    }
                }
               else if (CurrentUserInfo.ContainsPermit(Constants.Permit_DelTrace_Company))
                {
                    if (CurrentUserInfo.CompanyId.Equals(model.CompanyId))
                    {
                        strMsg = "{success:1,msg:'',data:{permit:true}}";
                        return true;
                    }
                    else
                    {
                        strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                        return false;
                    }
                }
               else if (CurrentUserInfo.ContainsPermit(Constants.Permit_DelTrace_Department))
                {
                    if (CurrentUserInfo.DepartId.Equals(model.DepartId))
                    {
                        if (!checkDepartPermit(context))
                        {
                            strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                            return false;
                        }
                        else
                        {
                            strMsg = "{success:1,msg:'',data:{permit:true}}";
                            return true;
                        }
                    }
                    else
                    {
                        strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                        return false;
                    }
                }
                else
                {
                    if (CurrentUserInfo.UserId.Equals(model.TractorId))
                    {
                        /*if (!checkDepartPermit(context))
                        {
                            strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                            return false;
                        }
                        else
                        {
                         */   strMsg = "{success:1,msg:'',data:{permit:true}}";
                            return true;
                       // }
                    }
                    else
                    {
                        strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                        return false;
                    }
                }
            }
        }
        strMsg = "{success:1,msg:'',data:{permit:true}}";
        return true;
    }
    //*******************************************
    //功能概要       ：部门内有无封盘解盘权限
    //参数説明       ：context 上下文
    //返回值説明     ：bool
    //功能詳細       ：部门内有无封盘解盘权限
    //作成者         ：chen.yugong 
    //作成日         ：2010-05-19
    //修改者         ：
    //修改日         ：
    //*******************************************
    public bool checkDepartPermit(HttpContext context)
    {
        //检查有无权限
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendFormat(" (Departid = '{0}' AND  Userid= '{1}') ", CurrentUserInfo.DepartId, CurrentUserInfo.UserId);
        sb.Append("AND (DelTrace = 1) ");
        DataSet ds = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetList(sb.ToString());
        if (ds.Tables[0].Rows.Count < 1)
        {
            return false;
        }
        return true;
    }
}